package com.wangling.servlet;

import com.wangling.model.User;
import com.wangling.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/do-register")
public class DoRegisterServlet extends HttpServlet {
    private final UserService userService = new UserService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String nickname = req.getParameter("nickname");
        String avatar = req.getParameter("avatar");
        String git = req.getParameter("git");
        String password = req.getParameter("password");

        User user = userService.register(username, nickname, avatar, git, password);

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();
        if (user != null) {
            HttpSession session = req.getSession();
            session.setAttribute("cerrentUser", user);
            writer.printf("<p>注册成功，请点击<a href='/blog0124/'>此处</a>跳转首页</p>\r\n");
        } else {
            writer.printf("<p>注册失败，请点击<a href='/blog0124/register.html'>此处</a>重新注册</p>\r\n");
        }

    }
}
